package org.yourscrum.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.yourscrum.domain.Story;
import org.yourscrum.domain.StoryRepository;
import org.yourscrum.domain.Task;

import java.util.List;

/**
 * @author Jettro Coenradie
 */
@Service("storyService")
public class StoryServiceImpl implements StoryService {
    private StoryRepository storyRepository;

    @Autowired
    public StoryServiceImpl(StoryRepository storyRepository) {
        this.storyRepository = storyRepository;
    }

    @Transactional(readOnly = true)
    public List<Story> listAllStories() {
        return storyRepository.listAllStories();
    }

    @Transactional(readOnly = true)
    public Story obtainStoryById(Long id) {
        Story story = storyRepository.obtainStoryById(id);

        return story;
    }

    @Transactional
    public Story createStory(String name, String description) {
        Story story = new Story(name);
        story.changeDescription(description);
        return storyRepository.createStory(story);
    }

    @Transactional
    public Story changeStory(long id, String name, String description) {
        Story story = storyRepository.obtainStoryById(id);
        story.changeDescription(description);
        story.changeName(name);
        return storyRepository.updateStory(story);
    }

    @Transactional
    public Story addTaskToStory(long storyId, String description, int estimatedHours) {
        Story story = storyRepository.obtainStoryById(storyId);
        Task task = story.addNewTask(description);
        task.changeEstimatedHours(estimatedHours);
        return storyRepository.updateStory(story);
    }

}
